<template>
  <div class="settings-container">
    <div class="settings-header">
      <h2>系统设置</h2>
    </div>
    
    <div class="settings-content">
      <el-card class="model-config">
        <template #header>
          <div class="card-header">
            <span>Ollama 配置</span>
            <el-tag 
              :type="serviceStatus.online ? 'success' : 'danger'"
              class="status-tag"
            >
              {{ serviceStatus.online ? '服务在线' : '服务离线' }}
            </el-tag>
          </div>
        </template>
        
        <el-form :model="modelConfig" label-width="120px">
          <!-- 基础配置 -->
          <div class="config-section">
            <h3 class="section-title">
              <el-icon><Setting /></el-icon>
              基础配置
            </h3>
            
            <el-form-item label="服务地址">
              <div class="input-with-status">
                <el-input 
                  v-model="modelConfig.endpoint" 
                  placeholder="http://localhost:11434"
                  clearable
                >
                  <template #append>
                    <el-button 
                      :type="serviceStatus.online ? 'success' : 'primary'"
                      link
                      :loading="testingConnection"
                      @click="testConnection"
                    >
                      测试连接
                    </el-button>
                  </template>
                </el-input>
              </div>
            </el-form-item>
          </div>

          <!-- 模型配置选项卡 -->
          <el-tabs v-model="activeTab" class="model-tabs">
            <!-- 对话模型配置 -->
            <el-tab-pane name="chat">
              <template #label>
                <span class="tab-label">
                  <el-icon><ChatDotRound /></el-icon>
                  对话模型
                </span>
              </template>

              <div class="tab-content">
                <el-form-item label="模型选择">
                  <el-select 
                    v-model="modelConfig.chat.model"
                    class="model-select"
                    placeholder="选择对话模型"
                    :loading="loadingModels"
                    @visible-change="handleModelSelectOpen"
                  >
                    <el-option
                      v-for="model in availableModels"
                      :key="model.name"
                      :label="model.name"
                      :value="model.name"
                    >
                      <div class="model-option">
                        <span class="model-name">{{ model.name }}</span>
                        <el-tag size="small" :type="model.status === 'ready' ? 'success' : 'warning'">
                          {{ model.status === 'ready' ? '已下载' : '未下载' }}
                        </el-tag>
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="温度">
                  <el-slider
                    v-model="modelConfig.chat.parameters.temperature"
                    :min="0"
                    :max="1"
                    :step="0.1"
                    show-input
                  />
                </el-form-item>

                <el-form-item label="Top P">
                  <el-slider
                    v-model="modelConfig.chat.parameters.top_p"
                    :min="0"
                    :max="1"
                    :step="0.1"
                    show-input
                  />
                </el-form-item>

                <el-form-item label="最大输出">
                  <el-input-number
                    v-model="modelConfig.chat.parameters.max_tokens"
                    :min="100"
                    :max="4096"
                    :step="100"
                  />
                </el-form-item>
              </div>
            </el-tab-pane>

            <!-- 嵌入模型配置 -->
            <el-tab-pane name="embedding">
              <template #label>
                <span class="tab-label">
                  <el-icon><Connection /></el-icon>
                  嵌入模型
                </span>
              </template>

              <div class="tab-content">
                <el-form-item label="模型选择">
                  <el-select 
                    v-model="modelConfig.embedding.model"
                    class="model-select"
                    placeholder="选择嵌入模型"
                    :loading="loadingModels"
                  >
                    <el-option
                      v-for="model in embeddingModels"
                      :key="model.name"
                      :label="model.name"
                      :value="model.name"
                    >
                      <div class="model-option">
                        <span class="model-name">{{ model.name }}</span>
                        <el-tag size="small" :type="model.status === 'ready' ? 'success' : 'warning'">
                          {{ model.status === 'ready' ? '已下载' : '未下载' }}
                        </el-tag>
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="分段大小">
                  <el-input-number
                    v-model="modelConfig.embedding.parameters.chunkSize"
                    :min="100"
                    :max="5000"
                    :step="100"
                  />
                </el-form-item>

                <el-form-item label="重叠长度">
                  <el-input-number
                    v-model="modelConfig.embedding.parameters.overlap"
                    :min="0"
                    :max="500"
                    :step="50"
                  />
                </el-form-item>

                <el-form-item label="批处理大小">
                  <el-input-number
                    v-model="modelConfig.embedding.parameters.batchSize"
                    :min="1"
                    :max="64"
                    :step="1"
                  />
                </el-form-item>

                <el-form-item label="启用缓存">
                  <el-switch
                    v-model="modelConfig.embedding.parameters.cache"
                  />
                </el-form-item>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-form>

        <div class="form-actions">
          <el-button type="primary" @click="handleSave" :loading="loading">
            保存配置
          </el-button>
          <el-button @click="handleReset">
            重置
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { useModelStore } from '@/store/model'
import { testOllamaConnection } from '@/api/model'
import { 
  Setting, Monitor, Connection, ChatRound, 
  Share, Loading, Select, Warning, ChatDotRound 
} from '@element-plus/icons-vue'

const modelStore = useModelStore()
const testingConnection = ref(false)
const serviceStatus = ref({ online: false })
const modelStatus = ref({
  chat: null,
  embedding: null
})

// 添加 loading 相关逻辑
const loading = ref(false)

// 初始化默认配置
const modelConfig = ref({
  endpoint: '',
  chat: {
    model: '',
    parameters: {
      temperature: 0,
      top_p: 0.1,
      top_k: 40,
      max_tokens: 2048
    }
  },
  embedding: {
    model: '',
    parameters: {
      chunkSize: 1000,
      overlap: 200,
      batchSize: 32,
      cache: true
    }
  }
})

const availableModels = ref([])
const embeddingModels = ref([])

// 添加选项卡激活状态
const activeTab = ref('chat')

// 测试连接
const testConnection = async () => {
  testingConnection.value = true
  try {
    const { data } = await testOllamaConnection(modelConfig.value.endpoint)
    console.log('Connection test response:', data) // 添加日志
    
    // 更宽松的状态判断
    serviceStatus.value.online = Boolean(
      data?.success || 
      data?.online || 
      data?.status === 'success' || 
      data?.connected
    )
    
    if (serviceStatus.value.online) {
      ElMessage.success('服务连接正常')
    } else {
      ElMessage.warning({
        message: '服务连接异常，请检查服务是否正常运行',
        duration: 3000
      })
    }
  } catch (error) {
    console.error('Connection test failed:', error)
    serviceStatus.value.online = false
    ElMessage.error({
      message: `连接失败: ${error.message || '请检查服务地址是否正确'}`,
      duration: 3000
    })
  } finally {
    testingConnection.value = false
  }
}

// 检查模型状态
const checkModelStatus = async () => {
  try {
    const status = await modelStore.getModelStatus()
    console.log('Model status updated:', status) // 添加日志
    
    // 更新服务状态
    serviceStatus.value.online = status.connected
    
    // 更新模型状态
    modelStatus.value = {
      chat: {
        ready: status.chat.ready,
        loading: status.chat.loading
      },
      embedding: {
        ready: status.embedding.ready,
        loading: status.embedding.loading
      }
    }
  } catch (error) {
    console.error('Failed to check model status:', error)
  }
}

// 加载配置
const loadConfig = async () => {
  try {
    const config = await modelStore.getConfig()
    modelConfig.value = {
      endpoint: config.endpoint,
      chat: {
        model: config.chat.model,
        parameters: {
          ...modelConfig.value.chat.parameters,
          ...config.chat.parameters
        }
      },
      embedding: {
        model: config.embedding.model,
        parameters: {
          ...modelConfig.value.embedding.parameters,
          ...config.embedding.parameters
        }
      }
    }
    
    // 获取可用模型列表
    const models = await modelStore.fetchModels()
    availableModels.value = models.filter(m => !m.name.includes('embed'))
    embeddingModels.value = models.filter(m => m.name.includes('embed'))
    
    // 先检查服务状态
    await testConnection()
    // 如果服务在线，再检查模型状态
    if (serviceStatus.value.online) {
      await checkModelStatus()
    }
  } catch (error) {
    console.error('Failed to load config:', error)
    ElMessage.error('加载配置失败')
  }
}

// 保存配置
const handleSave = async () => {
  loading.value = true
  const loadingInstance = ElLoading.service({
    text: '保存配置中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    await modelStore.updateConfig(modelConfig.value)
    ElMessage.success('配置保存成功')
    await checkModelStatus()
  } catch (error) {
    ElMessage.error(error.message || '保存配置失败')
    console.error('保存配置失败:', error)
  } finally {
    loading.value = false
    loadingInstance.close()
  }
}

// 重置配置
const handleReset = async () => {
  try {
    await loadConfig()
    ElMessage.success('配置已重置')
  } catch (error) {
    ElMessage.error('重置配置失败')
    console.error('重置配置失败:', error)
  }
}

// 定期检查状态
let statusCheckInterval
onMounted(() => {
  loadConfig()
  statusCheckInterval = setInterval(checkModelStatus, 30000) // 每30秒检查一次
})

onUnmounted(() => {
  if (statusCheckInterval) {
    clearInterval(statusCheckInterval)
  }
})

// 获取模型状态类型
const getModelStatusType = (status) => {
  if (!serviceStatus.value.online) return 'danger'
  if (status?.loading) return 'warning'
  if (status?.ready) return 'success'
  return 'danger'
}

// 获取模型状态文本
const getModelStatusText = (status) => {
  if (!serviceStatus.value.online) return '服务离线'
  if (status?.loading) return '加载中'
  if (status?.ready) return '已加载'
  return '未加载'
}

// 格式化模型大小
const formatSize = (size) => {
  if (!size) return '未知'
  const gb = size / 1024 / 1024 / 1024
  if (gb >= 1) {
    return `${gb.toFixed(1)}GB`
  }
  const mb = size / 1024 / 1024
  return `${mb.toFixed(1)}MB`
}
</script>

<style lang="scss" scoped>
.settings-container {
  height: 100vh;
  padding: $spacing-lg;
  background-color: var(--el-bg-color-page);
  
  .settings-header {
    margin-bottom: $spacing-lg;
    
    h2 {
      margin: 0;
      font-size: 18px;
      font-weight: 500;
      color: var(--el-text-color-primary);
    }
  }
  
  .settings-content {
    max-width: 900px;
    margin: 0 auto;
    
    .model-config {
      .config-section {
        &.basic-config {
          background-color: var(--el-fill-color-blank);
          border-radius: var(--el-border-radius-base);
          padding: 24px;
          
          .section-title {
            display: flex;
            align-items: center;
            gap: 8px;
            color: var(--el-text-color-primary);
            
            .el-icon {
              font-size: 18px;
              color: var(--el-color-primary);
            }
          }
        }
        
        margin-bottom: 32px;
        
        .section-title {
          font-size: 16px;
          font-weight: 500;
          color: var(--el-text-color-primary);
          margin: 0 0 20px;
          padding-bottom: 12px;
          border-bottom: 1px solid var(--el-border-color-light);
        }
      }
      
      :deep(.el-form) {
        max-width: 700px;
        margin: 0 auto;
        
        .el-form-item {
          margin-bottom: 24px;
          
          &.form-actions {
            margin-bottom: 0;
            margin-top: 32px;
            text-align: center;
            border-top: 1px solid var(--el-border-color-light);
            padding-top: 32px;
            
            .el-form-item__content {
              justify-content: center;
              gap: 12px;
            }
          }
          
          .input-with-status {
            display: flex;
            align-items: center;
            gap: $spacing-sm;
            
            .form-input {
              flex: 1;
              
              &.model-select {
                min-width: 300px;
              }
            }
            
            .status-tag {
              flex-shrink: 0;
              min-width: 64px;
              text-align: center;
            }
          }
        }
        
        .form-input {
          width: 100%;
        }
        
        .el-slider {
          margin-top: 8px;
        }
        
        .input-with-status {
          .status-tag {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            padding: 0 10px;
            height: 28px;
            
            .status-icon {
              font-size: 14px;
            }
          }
        }
        
        .el-input, .el-select {
          .el-input__wrapper {
            padding-left: 8px;
          }
          
          .el-input__prefix {
            color: var(--el-text-color-secondary);
          }
        }
      }
      
      .card-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        
        .status-tag {
          margin-left: $spacing-md;
        }
      }
    }

    .model-tabs {
      margin-top: 20px;

      .tab-label {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .el-icon {
          margin-right: 4px;
        }
      }

      .tab-content {
        padding: 20px 0;
      }
    }
  }

  .form-actions {
    margin-top: 24px;
    display: flex;
    justify-content: center;
    gap: 16px;
  }
}

.model-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  
  .model-name {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

:deep(.model-select-dropdown) {
  min-width: 300px !important;
  .el-select-dropdown__item {
    padding: 8px 12px;
  }
}
</style> 